package com.gph.saviorframework.mq.api.impl.rocketmq;

import com.alibaba.rocketmq.client.impl.producer.DefaultMQProducerImpl;
import com.alibaba.rocketmq.common.UtilAll;
import com.gph.saviorframework.mq.api.PropertyKeyConst;
import com.gph.saviorframework.mq.api.exception.MQClientException;
import com.gph.saviorframework.mq.api.impl.authority.SessionCredentials;
import com.gph.saviorframework.mq.api.impl.util.NameAddrUtils;

import java.util.Properties;

import static com.alibaba.rocketmq.common.UtilAll.getPid;

/**
 * Created by root on 16-7-10.
 */
public abstract class MQClientAbstract {

    protected String nameServerAddr = NameAddrUtils.getNameAdd();

    protected final Properties properties;

    protected final SessionCredentials sessionCredentials = new SessionCredentials();

    public MQClientAbstract(Properties properties){
        this.properties = properties;

        sessionCredentials.updateContent(properties);

        this.sessionCredentials.updateContent(properties);
        // 检测必须的参数
        if (null == this.sessionCredentials.getAccessKey() || "".equals(this.sessionCredentials.getAccessKey())) {
            throw new MQClientException("please set access key");
        }

        if (null == this.sessionCredentials.getSecretKey() || "".equals(this.sessionCredentials.getSecretKey())) {
            throw new MQClientException("please set secret key");
        }

        String property = this.properties.getProperty(PropertyKeyConst.NAMESRV_ADDR);
        if (property != null) {
            this.nameServerAddr = property;
            return;
        }
    }

    public String getNameServerAddr() {
        return nameServerAddr;
    }

    protected String buildIntanceName() {
        return Integer.toString(UtilAll.getPid())//
                + "#" + this.nameServerAddr.hashCode() //
                + "#" + this.sessionCredentials.getAccessKey().hashCode() + "#" + System.nanoTime();
    }

    protected void checkProducerServiceState(DefaultMQProducerImpl producer) {
        switch (producer.getServiceState()) {
            case CREATE_JUST:
                throw new MQClientException(String.format("You do not have start the producer[" + getPid() + "], %s", producer.getServiceState()));
            case SHUTDOWN_ALREADY:
                throw new MQClientException(String.format("Your producer has been shut down, %s", producer.getServiceState()));
            case START_FAILED:
                throw new MQClientException(String.format("When you start your service throws an exception, %s", producer.getServiceState()));
            case RUNNING:
                break;
            default:
                break;
        }
    }

}
